<template>
    <div class="teacher-attendance-settings">
        <div class="breadcrumb">
            <span>考勤管理</span> &gt; <span>教师考勤</span> &gt; <span>考勤时间设置</span>
        </div>

        <div class="tabs">
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/manage')">我的请假</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/approval')">请假审批</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/statistics')">考勤统计</div>
            <div class="tab-item active">考勤时间设置</div>
        </div>

        <div class="filter-bar">
            <el-select v-model="semester" placeholder="学期考勤" class="filter-item">
                <el-option label="2023-2024学年第一学期" value="2023-2024-1" />
                <el-option label="2023-2024学年第二学期" value="2023-2024-2" />
                <el-option label="2022-2023学年第一学期" value="2022-2023-1" />
                <el-option label="2022-2023学年第二学期" value="2022-2023-2" />
            </el-select>

            <el-button type="primary" @click="handleSearch" class="search-btn">查 询</el-button>
            <el-button @click="handleReset" class="reset-btn">重 置</el-button>
            <el-button type="primary" @click="handleAddRule" class="add-btn" icon="Plus">添加规则</el-button>
        </div>

        <div class="result-info">查询结果：共计 {{ tableData.length }} 条数据</div>

        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="academicYear" label="考勤学年" min-width="120" align="center" />
            <el-table-column prop="semester" label="考勤学期" min-width="120" align="center" />
            <el-table-column prop="startDate" label="学期开始时间" min-width="150" align="center" />
            <el-table-column prop="endDate" label="学期结束时间" min-width="150" align="center" />
            <el-table-column prop="startTime" label="考勤开始时间" min-width="120" align="center" />
            <el-table-column prop="endTime" label="考勤结束时间" min-width="120" align="center" />
            <el-table-column label="操作" min-width="180" align="center">
                <template #default="scope">
                    <el-button type="primary" @click="handleView(scope.row)" size="small" icon="View">
                        查看
                    </el-button>
                    <el-button type="primary" @click="handleEdit(scope.row)" size="small" icon="Edit">
                        编辑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑规则弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑考勤时间设置' : '新增考勤时间设置'" width="500px">
            <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="120px">
                <el-form-item label="考勤学年" prop="academicYear">
                    <el-select v-model="form.academicYear" placeholder="请选择学年" style="width: 100%">
                        <el-option label="2022年" value="2022年" />
                        <el-option label="2023年" value="2023年" />
                        <el-option label="2024年" value="2024年" />
                    </el-select>
                </el-form-item>
                <el-form-item label="考勤学期" prop="semester">
                    <el-select v-model="form.semester" placeholder="请选择学期" style="width: 100%">
                        <el-option label="上学期" value="上学期" />
                        <el-option label="下学期" value="下学期" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学期开始时间" prop="startDate">
                    <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期" style="width: 100%" />
                </el-form-item>
                <el-form-item label="学期结束时间" prop="endDate">
                    <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期" style="width: 100%" />
                </el-form-item>
                <el-form-item label="考勤开始时间" prop="startTime">
                    <el-time-picker v-model="form.startTime" format="HH:mm" placeholder="选择时间" style="width: 100%" />
                </el-form-item>
                <el-form-item label="考勤结束时间" prop="endTime">
                    <el-time-picker v-model="form.endTime" format="HH:mm" placeholder="选择时间" style="width: 100%" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting">
                        {{ isEdit ? '保存' : '添加' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 查看详情弹窗 -->
        <el-dialog v-model="viewDialogVisible" title="考勤时间设置详情" width="500px">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="考勤学年">{{ currentRule.academicYear }}</el-descriptions-item>
                <el-descriptions-item label="考勤学期">{{ currentRule.semester }}</el-descriptions-item>
                <el-descriptions-item label="学期开始时间">{{ currentRule.startDate }}</el-descriptions-item>
                <el-descriptions-item label="学期结束时间">{{ currentRule.endDate }}</el-descriptions-item>
                <el-descriptions-item label="考勤开始时间">{{ currentRule.startTime }}</el-descriptions-item>
                <el-descriptions-item label="考勤结束时间">{{ currentRule.endTime }}</el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="viewDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Plus, View, Edit } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const ruleFormRef = ref<FormInstance>()

// 查询条件
const semester = ref('')

// 表格数据
const tableData = ref([
    {
        id: '1',
        academicYear: '2022年',
        semester: '上学期',
        startDate: '2022-02-17',
        endDate: '2022-06-30',
        startTime: '8:30',
        endTime: '16:30'
    },
    {
        id: '2',
        academicYear: '2022年',
        semester: '下学期',
        startDate: '2022-09-01',
        endDate: '2023-01-15',
        startTime: '8:30',
        endTime: '16:30'
    }
])

// 弹窗相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const currentRule = ref({
    id: '',
    academicYear: '',
    semester: '',
    startDate: '',
    endDate: '',
    startTime: '',
    endTime: ''
})

// 表单数据
const form = reactive({
    id: '',
    academicYear: '',
    semester: '',
    startDate: '',
    endDate: '',
    startTime: '',
    endTime: ''
})

// 表单验证规则
const rules = {
    academicYear: [{ required: true, message: '请选择学年', trigger: 'change' }],
    semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
    startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
    endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

// 查询
function handleSearch() {
    if (semester.value) {
        const [year, term] = semester.value.split('-')
        const filteredData = tableData.value.filter(item => {
            return (
                item.academicYear.includes(year.substring(0, 4)) &&
                ((term === '1' && item.semester === '上学期') ||
                    (term === '2' && item.semester === '下学期'))
            )
        })
        ElMessage.success('查询成功')
        tableData.value = filteredData
    } else {
        ElMessage.warning('请选择学期')
    }
}

// 重置
function handleReset() {
    semester.value = ''
    // 重置为原始数据
    tableData.value = [
        {
            id: '1',
            academicYear: '2022年',
            semester: '上学期',
            startDate: '2022-02-17',
            endDate: '2022-06-30',
            startTime: '8:30',
            endTime: '16:30'
        },
        {
            id: '2',
            academicYear: '2022年',
            semester: '下学期',
            startDate: '2022-09-01',
            endDate: '2023-01-15',
            startTime: '8:30',
            endTime: '16:30'
        }
    ]
}

// 添加规则
function handleAddRule() {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
}

// 查看详情
function handleView(row: any) {
    currentRule.value = { ...row }
    viewDialogVisible.value = true
}

// 编辑规则
function handleEdit(row: any) {
    isEdit.value = true
    form.id = row.id
    form.academicYear = row.academicYear
    form.semester = row.semester
    form.startDate = row.startDate
    form.endDate = row.endDate
    form.startTime = row.startTime
    form.endTime = row.endTime
    dialogVisible.value = true
}

// 重置表单
function resetForm() {
    form.id = ''
    form.academicYear = ''
    form.semester = ''
    form.startDate = ''
    form.endDate = ''
    form.startTime = ''
    form.endTime = ''
}

// 提交表单
function submitForm() {
    ruleFormRef.value?.validate((valid) => {
        if (valid) {
            submitting.value = true
            setTimeout(() => {
                if (isEdit.value) {
                    // 编辑现有规则
                    const index = tableData.value.findIndex(item => item.id === form.id)
                    if (index !== -1) {
                        tableData.value[index] = { ...form }
                        ElMessage.success('修改成功')
                    }
                } else {
                    // 添加新规则
                    const newId = String(tableData.value.length + 1)
                    tableData.value.push({
                        id: newId,
                        academicYear: form.academicYear,
                        semester: form.semester,
                        startDate: formatDate(form.startDate),
                        endDate: formatDate(form.endDate),
                        startTime: formatTime(form.startTime),
                        endTime: formatTime(form.endTime)
                    })
                    ElMessage.success('添加成功')
                }
                submitting.value = false
                dialogVisible.value = false
            }, 500)
        } else {
            return false
        }
    })
}

// 格式化日期
function formatDate(date: any): string {
    if (!date) return ''
    if (typeof date === 'string') return date

    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 格式化时间
function formatTime(time: any): string {
    if (!time) return ''
    if (typeof time === 'string') return time

    const d = new Date(time)
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    return `${hours}:${minutes}`
}

// 导航到指定路由
function navigateTo(route: string) {
    router.push(route)
}
</script>

<style scoped>
.teacher-attendance-settings {
    padding: 0 20px;
}

.breadcrumb {
    display: flex;
    align-items: center;
    height: 50px;
    font-size: 14px;
    color: #606266;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 20px;
}

.tab-item {
    padding: 12px 20px;
    font-size: 14px;
    cursor: pointer;
    color: #606266;
    border-bottom: 2px solid transparent;
}

.tab-item.active {
    color: #409EFF;
    border-bottom: 2px solid #409EFF;
}

.filter-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;
}

.filter-item {
    width: 200px;
}

.search-btn,
.reset-btn {
    margin-left: 10px;
}

.add-btn {
    margin-left: auto;
}

.result-info {
    background-color: #ecf8ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    color: #409EFF;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}
</style>